import asyncio
import time
import json
from datetime import datetime
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import Dict, Any

from common.models import BaseLetterRequest, LetterResponse
from common.database import get_db, LaixinRecord, get_storage_adapter
from common.config import MAX_TEXT_LENGTH, SUMMARY_TARGET_LENGTH
from common.long_context_summary import async_map_reduce_summarize
from letter.services.letter_processor_service import LetterProcessorService
from letter.letter_logger import log_api_request, log_api_response, log_error
from letter.utils.async_utils import async_log_error

# 创建路由器
router = APIRouter(prefix="/api", tags=["来信件处理"])

# 全局变量，需要在主应用中初始化
CALL_RECORDS = {}
thread_pool = None
letter_processor_service = None


def set_global_variables(_call_records, _thread_pool):
    """设置全局变量，由主应用调用"""
    global CALL_RECORDS, thread_pool, letter_processor_service
    CALL_RECORDS = _call_records
    thread_pool = _thread_pool
    letter_processor_service = LetterProcessorService(_thread_pool)


@router.post("/getLetters", response_model=LetterResponse)
async def process_letter(
    request: BaseLetterRequest,
):
    """
    处理来信件的主要接口

    Args:
        request: 包含信访件信息的请求对象

    Returns:
        处理结果
    """
    start_time = time.time()

    try:
        # 检查文本长度，如果超过阈值则进行摘要处理
        original_length = len(request.caseIntruction)
        processed_content = request.caseIntruction
        
        if original_length > MAX_TEXT_LENGTH:
            print(f"文本长度 {original_length} 超过阈值 {MAX_TEXT_LENGTH}，开始进行摘要处理...")
            try:
                processed_content = await async_map_reduce_summarize(
                    request.caseIntruction, 
                    target_length=SUMMARY_TARGET_LENGTH
                )
                print(f"摘要处理完成，长度从 {original_length} 压缩到 {len(processed_content)}")
            except Exception as e:
                print(f"摘要处理失败: {e}")
                # 如果摘要失败，截断到最大长度
                processed_content = request.caseIntruction[:MAX_TEXT_LENGTH]
                print(f"使用截断文本，长度: {len(processed_content)}")
        else:
            print(f"文本长度 {original_length} 在阈值范围内，无需摘要处理")

        # 实时记录调用请求到内存
        CALL_RECORDS[request.bh] = {
            "bh": request.bh,
            "txm": request.txm,
            "startTime": datetime.fromtimestamp(start_time).strftime(
                "%Y-%m-%d %H:%M:%S"
            ),
            "status": "处理中",
            "processTime": 0,
            "requestInfo": request.dict(),
            "responseInfo": None,
            "errorInfo": None,
        }

        # 使用存储适配器创建记录（使用处理后的文本）
        storage = get_storage_adapter()
        db_record = storage.create_laixin_record(
            bh=request.bh,
            txm=request.txm,
            start_time=datetime.fromtimestamp(start_time),
            status="处理中",
            case_instruction=processed_content,
        )

        # 记录请求信息
        await log_api_request_async(request.bh, request.dict(), start_time)

        # 处理信访件（使用处理后的文本）
        result = await letter_processor_service.process_letter_async(
            bh=request.bh, case_content=processed_content, txm=request.txm
        )

        # 计算处理时间
        processing_time = time.time() - start_time

        # 实时更新CALL_RECORDS中的成功信息
        if request.bh in CALL_RECORDS:
            CALL_RECORDS[request.bh]["status"] = "成功"
            CALL_RECORDS[request.bh]["responseInfo"] = result
            CALL_RECORDS[request.bh]["processTime"] = processing_time

        # 更新存储记录
        storage.update_laixin_record(
            request.bh,
            status="成功",
            response=json.dumps(result, ensure_ascii=False),
            process_time=processing_time
        )

        # 记录响应信息
        await log_api_response_async(request.bh, result, processing_time)

        return LetterResponse(success="true", message="处理成功", data=result)

    except Exception as e:
        error_msg = f"处理失败: {str(e)}"

        # 实时更新CALL_RECORDS中的失败信息
        if request.bh in CALL_RECORDS:
            CALL_RECORDS[request.bh]["status"] = "失败"
            CALL_RECORDS[request.bh]["errorInfo"] = {"message": error_msg}

        # 更新存储记录为失败
        if "db_record" in locals() and db_record:
            storage.update_laixin_record(
                request.bh,
                status="失败",
                error_info=error_msg
            )

        # 记录错误信息
        await async_log_error(request.bh, error_msg, thread_pool)

        # 计算处理时间
        processing_time = time.time() - start_time

        # 记录响应信息（错误情况）
        error_result = {
            "bh": request.bh,
            "txm": request.txm,
            "xflb": "",
            "wtxx": {
                "wtzy": "",
                "fl": [],
                "tygjz": [],
                "zdygjz": [],
                "bs": {"yy": "", "sggb": "", "sfcf": ""},
            },
            "fyrs": [],
            "bfyrs": [],
        }
        await log_api_response_async(request.bh, error_result, processing_time)

        raise HTTPException(status_code=500, detail=error_msg)


async def log_api_request_async(bh: str, request_data: dict, start_time: float):
    """异步记录API请求"""
    await asyncio.get_event_loop().run_in_executor(
        thread_pool, log_api_request, bh, request_data, start_time
    )


async def log_api_response_async(bh: str, response_data: dict, processing_time: float):
    """异步记录API响应"""
    await asyncio.get_event_loop().run_in_executor(
        thread_pool, log_api_response, bh, response_data, processing_time
    )
